package com.atguigu.thread2;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CyclicBarrierTest {
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        Lock lock = new ReentrantLock();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("救出爷爷了");
        });
        lock.lock();
        try {
            for (int i = 1; i <= 7; i++) {
                int finalI = i;
                new Thread(()->{System.out.println(finalI+"娃");
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }, Thread.currentThread().getName()).start();

            }
        } finally {
            lock.unlock();
        }
    }
}
